package com.lsh.oauth2.controller;

import com.lsh.common.constant.Constants;
import com.lsh.common.util.AjaxResult;
import com.lsh.oauth2.dto.LoginDto;
import com.lsh.oauth2.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/9/17 9:31 上午
 * @desc ：
 */
@RestController
public class LoginController {
    @Autowired
    LoginService loginService;


    @GetMapping("/login")
    public AjaxResult login(LoginDto loginDto){
        AjaxResult ajax = AjaxResult.success();
        String token = loginService.login(loginDto.getUsername(), loginDto.getPassword(), loginDto.getCode(), loginDto.getUuid());
        System.out.println(token);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * TODO SecurityContextHolder.getContext().getAuthentication() 无法获得当前认证的用户的信息，只能匿名 2021年09月24日17:32:47
     * @return
     */
    public String getUserName(){
        String username = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println("-----authentication:"+authentication);
        Object principal = authentication.getPrincipal();
        if (principal == null){
            username = "匿名";
        }else {
            if (principal instanceof UserDetails){
                UserDetails userDetails = (UserDetails) principal;
                System.out.println("UserDetails:"+userDetails);
                username = userDetails.getUsername();
            }else{
                username = principal.toString();
                System.out.println("principal.toString():"+principal.toString());
            }

        }

        return username;
    }
}
